//
//  LiveDetailViewController.m
//  AndCampus
//
//  Created by 史宵宵 on 2017/12/12.
//  Copyright © 2017年 史宵宵. All rights reserved.
//

#import "LiveDetailViewController.h"
#import "LiveClassRoomTableViewCell.h"
#import "LiveCommentTableViewCell.h"
#import "XHInputView.h"
#import "XXAVPlayer.h"
#import "PayActivityInforViewController.h"

@interface LiveDetailViewController ()<XHInputViewDelagete,XXAVPlayerDelegate>
@property (nonatomic,strong) ClassRoomInfo *classRoomInfo;

@property (nonatomic ,strong) NSMutableArray<NSLayoutConstraint *> *array;
@property (nonatomic,strong) NSMutableArray *commentDataArray;
@property (nonatomic,weak) XXAVPlayer *playView;

@property (nonatomic ,strong) NSMutableArray<NSLayoutConstraint *> *sliderArray;

@property (nonatomic, strong) XHInputView *inputViewStyleDefault;

@end

@implementation LiveDetailViewController


-(NSMutableArray *)commentDataArray{
    if (!_commentDataArray) {
        _commentDataArray = [NSMutableArray array];
    }
    return _commentDataArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self creatDataList];
    self.tableView.separatorStyle=UITableViewCellSeparatorStyleSingleLine;
    
    
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([LiveClassRoomTableViewCell class]) bundle:nil] forCellReuseIdentifier:@"LiveClassRoomCell"];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([LiveCommentTableViewCell class]) bundle:nil] forCellReuseIdentifier:@"LiveCommentTableViewCell"];
    
//    self.inputViewStyleDefault = [self inputViewWithStyle:InputViewStyleDefault];
//    self.inputViewStyleDefault.delegate = self;
//    [self.view addSubview:self.inputViewStyleDefault];
//    [self.inputViewStyleDefault show];
}
- (void)creatFootView{
    self.title = self.classRoomInfo.course_name;
    
    if ([self.classRoomInfo.can_message isEqualToString:@"1"]) {
        [self creatMessageView];
        self.tableView.frame = CGRectMake(0, 0, kScreenW, kScreenH - 64 - 44);
    }
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame=CGRectMake(0, 0, 30, 40);
    button.tag = 9000;
    [button addTarget:self action:@selector(collectionClassRoom:) forControlEvents:UIControlEventTouchUpInside];
    button.adjustsImageWhenHighlighted = NO;
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [button setImage:[self.classRoomInfo.favourite_history isEqualToString:@"1"]?[UIImage imageNamed:@"class_collection"]:[UIImage imageNamed:@"class_disCollection"] forState:UIControlStateNormal];
    button.imageView.contentMode=UIViewContentModeScaleAspectFit;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:button];
    
}
- (void)creatMessageView{
    UIView *footView = [[UIView alloc]init];
    footView.backgroundColor = [UIColor whiteColor];
    footView.frame = CGRectMake(0, kScreenH - 108, kScreenW, 44);
    [self.view addSubview:footView];
    
    UIButton *send = [[UIButton alloc]init];
    send.backgroundColor = [UIColor groupTableViewBackgroundColor];
    send.clipsToBounds = YES;
    send.layer.cornerRadius = 3;
    send.frame = CGRectMake(10, 4, kScreenW - 60 - 30, 34);
    [send addTarget:self action:@selector(sendMessage) forControlEvents:UIControlEventTouchUpInside];
    [footView addSubview:send];
    
    UILabel *plLabel = [[UILabel alloc]init];
    plLabel.frame = CGRectMake(10, 7, 100, 20);
    plLabel.textColor = [UIColor lightGrayColor];
    plLabel.text = @"我来说两句";
    plLabel.font = [UIFont systemFontOfSize:14];
    [send addSubview:plLabel];
    
    UIButton *sendButton = [UIButton buttonWithType:UIButtonTypeCustom];
    sendButton.frame = CGRectMake(kScreenW - 60 - 10, 5, 60, 34);
    sendButton.backgroundColor = KBACKNAVIGATIONCOLOR;
    sendButton.clipsToBounds = YES;
    sendButton.layer.cornerRadius = 3;
    [sendButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [sendButton setTitle:@"发送" forState:UIControlStateNormal];
    [sendButton addTarget:self action:@selector(sendMessage) forControlEvents:UIControlEventTouchUpInside];
    sendButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [footView addSubview:sendButton];
}
- (void)sendMessage{
    __weak typeof(self) weakSelf = self;
    self.inputViewStyleDefault = [self inputViewWithStyle:InputViewStyleDefault];
    self.inputViewStyleDefault.delegate = self;
    [self.view addSubview:self.inputViewStyleDefault];
    /** 发送按钮点击事件 */
    self.inputViewStyleDefault.sendBlcok = ^(NSString *text) {
        [weakSelf.inputViewStyleDefault hide];//隐藏输入框
        
        YJNetWorkManger *yjNetWorkManger =  [YJNetWorkManger shareManager];
        NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
        [dic setValue:weakSelf.classRoomInfo.course_id forKey:@"courseId"];   //动态的topicId 赞目标id
        [dic setValue:[Global getUserTokenInfo] forKey:@"token"]; //用户的token
        [dic setValue:text forKey:@"context"]; //评论内容
        [yjNetWorkManger requestType:POST andURL:[JSPathUtil urlAppCourseAddCourseComment] andParmas:dic andComplition:^(id response, BOOL isuccess) {
            if (isuccess) {
                [Global showActivityWithView:weakSelf.view withText:@"发表留言成功"];
                [weakSelf.tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationNone];
            }
        }];
        
    };
    [self.inputViewStyleDefault show];
}
-(XHInputView *)inputViewWithStyle:(InputViewStyle)style{
    
    XHInputView *inputView = [[XHInputView alloc] initWithStyle:style];
    //设置最大输入字数
    inputView.maxCount = 50;
    //输入框颜色
    inputView.textViewBackgroundColor = [UIColor groupTableViewBackgroundColor];
    //占位符
    inputView.placeholder = @"我来说两句";
    return inputView;
}
- (void)creatDataList{
    
    YJNetWorkManger *yjNetWorkManger =  [YJNetWorkManger shareManager];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setValue:@"1" forKey:@"page"];   //页数 默认1
    [dic setValue:KREFRESHROWS forKey:@"rows"];   //每页数量
    [dic setValue:[Global getUserTokenInfo] forKey:@"token"]; //用户的token
    [dic setValue:self.liveDetailId forKey:@"courseId"];    //课程id
    [yjNetWorkManger requestType:POST andURL:[JSPathUtil urlAppCourseGetCourseDetail] andParmas:dic andComplition:^(id response, BOOL isuccess) {
        if (isuccess) {
            [self.commentDataArray removeAllObjects];
            self.classRoomInfo = [ClassRoomInfo mj_objectWithKeyValues:response[@"courseDetail"]];
            NSArray *liveArray = [NSArray arrayWithArray:response[@"list"]];
            for (int i = 0; i < liveArray.count; i++) {
                [self.commentDataArray addObject:[LiveCommentInfo mj_objectWithKeyValues:liveArray[i]]];
            }
            [self creatFootView];
            [self initVideoView];
            [self.tableView reloadData];
        }
    }];
}
- (NSInteger )numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section) {
        return self.commentDataArray.count;
    }
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (!indexPath.section) {
        LiveClassRoomTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"LiveClassRoomCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.classRoomInfo = self.classRoomInfo;
        cell.imageType = @"detail";
        __weak typeof(self) unself = self;
        cell.payLiveClassBlack = ^(ClassRoomInfo *classRoomInfo) {
            PayActivityInforViewController *payActivityInforVC = [[PayActivityInforViewController alloc]init];
            payActivityInforVC.modalPresentationStyle = UIModalPresentationOverCurrentContext;
            payActivityInforVC.moneyStr = unself.classRoomInfo.source_price;
            payActivityInforVC.numId = [NSString stringWithFormat:@"%@",unself.classRoomInfo.course_id];
            payActivityInforVC.titleStr = unself.classRoomInfo.course_name;
            payActivityInforVC.paySuccessBlack = ^{
                [unself initVideoView];
            };
            UIViewController *appRootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
            [appRootVC presentViewController:payActivityInforVC animated:YES completion:^{
                
            }];
        };
        return cell;
    }else if (indexPath.section == self.tableView.numberOfSections - 1){
        UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"cell"];
        if (!cell) {
            cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            UIImageView *commentImageView=[[UIImageView alloc]initWithFrame:CGRectMake( 0, 0, 20, 20)];
            commentImageView.tag = 2000;
            commentImageView.contentMode=UIViewContentModeScaleAspectFit;
            [cell.contentView addSubview:commentImageView];
        }
        NSArray *imageArray = [NSArray arrayWithArray:self.classRoomInfo.teacher_content];
        UIImageView *commentImageView = [cell.contentView viewWithTag:2000];
        if (!imageArray.count || strIsEmpty(imageArray[0])) {
            commentImageView.frame=CGRectZero;
            [self removeallSubViews:commentImageView];
        }
        else
        {
            commentImageView.frame= CGRectMake(0, 0, kScreenW, imageArray.count? imageArray.count*kScreenW * 2 : 0);
            for (int i=0; i < imageArray.count; i++) {
                UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectMake(0, kScreenW * 2 * i, kScreenW, kScreenW * 2)];
                [imageView sd_setImageWithURL:[NSURL URLWithString:imageArray[i]] placeholderImage:KRECOMMENDLISTDEFAULT];
                imageView.tag=100+i;
                imageView.backgroundColor= [UIColor clearColor];
                imageView.contentMode=UIViewContentModeScaleToFill;
                [commentImageView addSubview:imageView];
            }
        }
        return cell;
    }
    LiveCommentTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"LiveCommentTableViewCell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.liveCommentInfo = self.commentDataArray[indexPath.row];
    return cell;
}
/**
 *  移除视图
 *
 *  @param supView 父视图
 */
- (void )removeallSubViews:(UIView *)supView{
    for (id obj in supView.subviews) {
        [obj removeFromSuperview];
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (!indexPath.section) {
        return 100;
    }else if (indexPath.section == self.tableView.numberOfSections - 1){
        return self.classRoomInfo.teacher_content.count*kScreenW * 2;
    }
    return [tableView fd_heightForCellWithIdentifier:@"LiveCommentTableViewCell" cacheByIndexPath:indexPath configuration:^(LiveCommentTableViewCell* cell) {
        // 配置 cell 的数据源，和 "cellForRow" 一致
        cell.liveCommentInfo = self.commentDataArray[indexPath.row];
    }];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (!section) {
        UIView *view = [[UIView alloc]init];
        view.frame = CGRectMake(0, 0, kScreenW, 0.01);
        view.backgroundColor = KBACKGROUNDCOLOR;

        return view;
    }
    UIView *view = [[UIView alloc]init];
    view.frame = CGRectMake(0, 0, kScreenW, 44);
    view.backgroundColor = [UIColor whiteColor];
    
    UILabel *sepLabel = [[UILabel alloc]init];
    sepLabel.frame = CGRectMake(0, 10, 3, 24);
    sepLabel.backgroundColor = KBACKNAVIGATIONCOLOR;
    [view addSubview:sepLabel];
    
    UILabel *titleLabel = [[UILabel alloc]init];
    titleLabel.frame = CGRectMake(10, 12, kScreenW - 20, 20);
    titleLabel.text = section==1?@"留言板":@"课程详情";
    titleLabel.font = [UIFont systemFontOfSize:16];
    [view addSubview:titleLabel];
    
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (!section) {
        return 0.01;
    }
    return 44;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
   
    UIView *view = [[UIView alloc]init];
    view.frame = CGRectMake(0, 0, kScreenW, 10);
    view.backgroundColor = KBACKGROUNDCOLOR;
    if (section == 2) {
        view.frame = CGRectMake(0, 0, kScreenW, 0.01);
    }
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 2) {
        return 0.01f;
    }
    return 10.01f;
}
#pragma mark - 收藏 / 取消收藏
- (void)collectionClassRoom:(UIButton*)sender{
    YJNetWorkManger *yjNetWorkManger =  [YJNetWorkManger shareManager];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setValue:self.classRoomInfo.course_id forKey:@"courseId"];   //动态的topicId 赞目标id
    [dic setValue:[Global getUserTokenInfo] forKey:@"token"]; //用户的token
     NSString *url = [self.classRoomInfo.favourite_history isEqualToString:@"1"]? [JSPathUtil urlAppCourseDeleteFavourite]: [JSPathUtil urlAppCourseSetFavourite];
    
    [yjNetWorkManger requestType:POST andURL:url andParmas:dic andComplition:^(id response, BOOL isuccess) {
        if (isuccess) {
            [Global showActivityWithView:self.view withText:[self.classRoomInfo.favourite_history isEqualToString:@"1"]?@"取消收藏成功":@"收藏成功"];
            self.classRoomInfo.favourite_history = [self.classRoomInfo.favourite_history isEqualToString:@"1"]?@"0":@"1";
            [sender setImage:[self.classRoomInfo.favourite_history isEqualToString:@"1"]?[UIImage imageNamed:@"class_collection"]:[UIImage imageNamed:@"class_disCollection"] forState:UIControlStateNormal];
        }
    }];
}
- (void)initVideoView {
    if ([self.classRoomInfo.live_status isEqualToString:@"1"] && ![self.classRoomInfo.buyHistory isEqualToString:@"2"]) {
        NSString *path = self.classRoomInfo.videoUrl;
        CGRect rect = CGRectMake(0, 0, self.view.bounds.size.width, 210);
        
        XXAVPlayer *playView = [[XXAVPlayer alloc] initWithFrame:rect];
        
        playView.delegate = self;
        
        self.tableView.tableHeaderView = playView;
        
        
        NSString *videoPath = [path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSURL *url = [NSURL URLWithString:videoPath];
        [playView setupPlayerWith:url];
        self.playView = playView;
    }else{
        UIImageView *imageView = [[UIImageView alloc]init];
        imageView.userInteractionEnabled = YES;
        imageView.frame = CGRectMake(0, 0, self.view.bounds.size.width, 210);
        [imageView sd_setImageWithURL:[NSURL URLWithString:self.classRoomInfo.logo] placeholderImage:KRECOMMENDLISTDEFAULT];
        
        UIButton *isVideoButton = [[UIButton alloc]init];
        isVideoButton.frame = CGRectMake((kScreenW - 50)/2, (210-50)/2, 50, 50);
        [isVideoButton setImage:[UIImage imageNamed:@"class_live_begin"] forState:UIControlStateNormal];
        [isVideoButton addTarget:self action:@selector(isBuyHistory) forControlEvents:UIControlEventTouchUpInside];
        [imageView addSubview:isVideoButton];
        
        self.tableView.tableHeaderView = imageView;
    }
}

- (void)isBuyHistory{
    [Global showActivityWithView:self.view withText:@"您还没有购买"];
}
// LPAVPlayer delegate  ----- 状态提示
- (void)promptPlayerStatusOrErrorWith:(LPAVPlayerStatus)status
{
    switch (status) {
        case LPAVPlayerStatusLoadingVideo:// 开始准备
            
            //            [self.activity startAnimating];
            
            break;
            
        case LPAVPlayerStatusReadyToPlay:{// 准备完成
            int time = [Global callDatePoor:self.classRoomInfo.live_begin_time];//      self.classRoomInfo.live_begin_time //开始直播时间
//            int time = [Global callDatePoor:@"2017-12-26 16:28:30"];//测试
            [self.playView seekPlayerTimeTo:time];
            //            [self.activity stopAnimating];
            //            [self.playOrPause setTitle:@"暂停" forState:UIControlStateNormal];
            //            self.slider.maximumValue = _playView.totalTime;
            //            self.slider.value = 0;
            //            self.loadProgress.progress = 0;
        }
            break;
            
            
            
        default:
            break;
    }
}
// LPAVPlayer delegate  ----- 刷新数据
- (void)refreshDataWith:(NSTimeInterval)totalTime Progress:(NSTimeInterval)currentTime LoadRange:(NSTimeInterval)loadTime
{
    
    //    [self.loadProgress setProgress:(loadTime/totalTime) animated:YES];
    //
    //    [self.slider setValue:currentTime animated:YES];
    //
    //    self.timeLabel.text = [NSString stringWithFormat:@"%@/%@",[self otherConvertTimeFormat:currentTime],[self otherConvertTimeFormat:totalTime]];
}

- (NSString *)otherConvertTimeFormat:(NSInteger)time
{
    NSString *needStr = @"";
    
    if (time < 3600) {
        
        needStr =  [NSString stringWithFormat:@"%02li:%02li",lround(floor(time/60.f)),lround(floor(time/1.f))%60];
        
    } else {
        
        needStr =  [NSString stringWithFormat:@"%02li:%02li:%02li",lround(floor(time/3600.f)),lround(floor(time%3600)/60.f),lround(floor(time/1.f))%60];
        
    }
    return needStr;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
